<?php
namespace sessions;

class PersistentSessionHandler extends MysqlSessionHandler
{
	use PersistentProperties;

    /** Write the session data to the database

    */

	public function write($session_id, $data)
    {
          try {
            $sql ="INSERT INTO $this->table_sess (
            $this->col_sid, $this->col_expiry,$this->col_data, $this->col_ukey)    
            VALUES (:sid, :expiry, :data, :key) 
            ON DUPLICATE KEY UPDATE $this->col_expiry = :expiry, $this->col_data = :data";
        $stmt = $this->db->prepare($sql);
        $stmt->bindParam(':sid', $session_id);//klopt
        $stmt->bindParam(':expiry', $this->expiry, \PDO::PARAM_INT);//klopt
        $stmt->bindParam(':data', $data);//klopt
        $stmt->bindParam(':key', $_SESSION[$this->sess_ukey]);//self added for serverlog purposes
        $stmt->execute();
        if (isset($_SESSION[$this->sess_persist]) || isset($_SESSION[$this->cookie])) {
        	$this->storeAutologinData($data);
        }
        return true;                   
               } catch (\PDOException $e){
            if ($this->db->inTransaction()) {
                $this->db->rollBack();
            } 
            throw $e;
        }
    }

       /** Copies the user's session data to the autologin table

    */

    protected function storeAutologinData($data)
    {
        // get the userkey if it is not already stored as a session variable
    	if (!isset($_SESSION[$this->sess_ukey])) {
    		$sql = "SELECT $this->col_ukey FROM $this->table_users WHERE $this->col_name = :username";
    		$stmt = $this->db->prepare($sql);
    		$stmt->bindParam(':username',$_SESSION[$this->sess_uname]);//klopt
    		$stmt->execute();
    		$_SESSION[$this->sess_ukey] = $stmt->fetchColumn();
    	}

        // copy the session data to the autologin table
    	$sql = "UPDATE $this->table_autologin SET $this->col_data = :data WHERE $this->col_ukey = :key"; 
    	$stmt = $this->db->prepare($sql);
		$stmt->bindParam(':data', $data);//klopt
		$stmt->bindParam(':key', $_SESSION[$this->sess_ukey]);//klopt
    	$stmt->execute();
    }

}

?>